// Copyright 2011 Abhishek Kulkarni. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"bytes"
	"flag"
	"go/parser"
	"go/printer"
	"go/scanner"
        "go/token"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

var (
	fset     = token.NewFileSet()
	exitCode = 0
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: goprop [path ...]\n")
	flag.PrintDefaults()
	os.Exit(2)
}

const (
	tabWidth    = 8
	parserMode  = parser.ParseComments
	printerMode = printer.TabIndent | printer.UseSpaces
)

var printConfig = &printer.Config{
	printerMode,
	tabWidth,
}

func report(err os.Error) {
	scanner.PrintError(os.Stderr, err)
	exitCode = 2
}

func walkDir(path string) {
	v := make(fileVisitor)
	go func() {
		filepath.Walk(path, v, v)
		close(v)
	}()
	for err := range v {
		if err != nil {
			report(err)
		}
	}
}

type fileVisitor chan os.Error

func (v fileVisitor) VisitDir(path string, f *os.FileInfo) bool {
	return true
}

func (v fileVisitor) VisitFile(path string, f *os.FileInfo) {
	if isPropFile(f) {
		v <- nil // synchronize error handler
		if err := processFile(path, false); err != nil {
			v <- err
		}
	}
}

func isPropFile(f *os.FileInfo) bool {
	// ignore non-Prop files
	return f.IsRegular() && !strings.HasPrefix(f.Name, ".") && strings.HasSuffix(f.Name, ".prop")
}

func processFile(filename string, useStdin bool) os.Error {
	var f *os.File
	var err os.Error
	var buf bytes.Buffer

	if useStdin {
		f = os.Stdin
	} else {
		f, err = os.Open(filename)
		if err != nil {
			return err
		}
		defer f.Close()
	}

	src, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}

	file, err := parser.ParseFile(fset, filename, src, parserMode)
	if err != nil {
		return err
	}

	// Apply all fixes to file.
	newFile := file
	addImport(newFile, "goprop.googlecode.com/hg/goprop")
	if transformAST(newFile) {
		// AST changed.
		// Print and parse, to update any missing scoping
		// or position information for subsequent fixers.
		buf.Reset()
		_, err = printConfig.Fprint(&buf, fset, newFile)
		if err != nil {
			return err
		}
		newSrc := buf.Bytes()
		newFile, err = parser.ParseFile(fset, filename, newSrc, parserMode)
		if err != nil {
			return err
		}
	}

	buf.Reset()
	_, err = printConfig.Fprint(&buf, fset, file)
	if err != nil {
		return err
	}
	newSrc := buf.Bytes()

	if useStdin {
		os.Stdout.Write(newSrc)
		return nil
	}

	return ioutil.WriteFile(f.Name(), newSrc, 0)
}

func main() {

	flag.Usage = usage
	flag.Parse()

	if flag.NArg() == 0 {
		if err := processFile("standard input", true); err != nil {
			report(err)
		}
		os.Exit(exitCode)
	}

	for i := 0; i < flag.NArg(); i++ {
		path := flag.Arg(i)
		switch dir, err := os.Stat(path); {
		case err != nil:
			report(err)
		case dir.IsRegular():
			if err := processFile(path, false); err != nil {
				report(err)
			}
		case dir.IsDirectory():
			walkDir(path)
		}
	}

	os.Exit(exitCode)
}
